<template>
  <div>
    <el-dialog :model-value="visible" :close-on-click-modal="false" title="新增结算方式" width="500" @close="cls">
      <!--表单-->
      <el-form ref="ruleFormRef" style="max-width: 400px" :model="ruleForm" label-width="100px" status-icon>
        <div style="height:60px"></div>
        <el-form-item label="名称" >
          <el-input v-model="ruleForm.name" />
        </el-form-item>
        <div style="height:60px"></div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="save">保存</el-button>
          <el-button @click="cls">不保存关闭</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>
<script setup>
import { ref } from 'vue';
import { ElMessage } from "element-plus";
import { saveDict, updateDict } from '@/api/settings/dictionary.jsx'
//声明属性
const props = defineProps({
  "visible": {
    type: Boolean,
    default: false
  }
})
//声明事件
const emits = defineEmits(["close", "refresh"])
//表明引用，要求响应对象与表单属性ref的值保持一致
const ruleFormRef = ref(null)
//表单数据
const ruleForm = ref({
  name: "",
  codes: "payway"
})

//保存
async function save() {
  //调用表单校验 异步的
  let valid = await ruleFormRef.value.validate(valid => {
  });
  if (!valid)
    return;
  let res;
  //判断当前是修改还是保存
  if (ruleForm.value.id) {
    //修改
    res = await updateDict(ruleForm.value)
  } else {
    res = await saveDict(ruleForm.value);
  }
  //验证通过，提交表单
  //等待接口返回数据以后再继续执行
  if (res.code == 200) {
    ElMessage({
      message: '保存成功',
      type: 'success'
    })
    //关闭窗口
    cls();
    //通知父窗口刷新数据
    emits("refresh");
  }
}

//组件显示时调用的初始化方法
function init(data) {
  if (data) {
    //说明是修改
    ruleForm.value = data;
  } else {
    ruleForm.value = {
      name: "",
      codes: "payway"
    }
  }
}
//暴露
defineExpose({ init })

//关闭窗口
function cls() {
  //抛出自定义事件
  emits("close");
}
</script>